import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer1 {
    private DatagramSocket socket = null;

    //指定端口号
    public UdpEchoServer1(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        //启动服务器
        System.out.println("服务器启动");
        while (true){
            //每循环一次，相当于处理一次请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //把读到的二进制数据转换成字符串。
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.根据请求，计算响应
            String respond = process(request);
            //3.将响应返回客户端
            DatagramPacket respondPacket = new DatagramPacket(respond.getBytes(),respond.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(respondPacket);
            //4.打印日志
            System.out.printf("[%s : %d] req:%s  resp:%S",requestPacket.getAddress(),respondPacket.getPort(),request,respond);
            System.out.println();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
